package com.msti.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.msti.entity.Batch;
import com.msti.entity.Student;
import com.msti.entity.Student_batch;
import com.msti.service.BatchMgtDAO;
import com.msti.service.BatchMgtDAOImpl;
import com.msti.service.StudentBatchDAOImpl;
import com.msti.service.StudentBatchMgtDAO;
import com.msti.service.StudentDAO;
import com.msti.service.StudentDAOImpl;
import com.msti.utility.JDBCCon;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Student student = (Student)request.getSession().getAttribute("student");
		//student.setPictureURL(request.getParameter("pictureURL"));
		BatchMgtDAO batchMgtDAO = new BatchMgtDAOImpl();
		StudentDAO studentDetail = new StudentDAOImpl();
		StudentBatchMgtDAO studentBatchMgtDAO = new StudentBatchDAOImpl();
		studentDetail.doRegister(student);
		String DOB = (String)request.getSession().getAttribute("stdDob");
		String query = "update Student set dateOfBirth='"+DOB+"' where studentID='"+student.getStudentID()+"'";
		Connection con = JDBCCon.getConnection();
		Statement statement;
		try {
			statement = con.createStatement();
			statement.executeUpdate(query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JDBCCon.closeConnection();
		String [] courses =(String[]) request.getSession().getAttribute("courses");
		for(String sr : courses)
		{
			System.out.println(sr);
		}
		for(String cId : courses){
			Batch batch = batchMgtDAO.getBatchByCourseId(Long.parseLong(cId));
			Student_batch studentBatch= new Student_batch();
			studentBatch.setBatch_id(batch.getId());
			studentBatch.setStudent_id(student.getStudentID());
			studentBatch.setStudent_state(false);
			studentBatchMgtDAO.insert(studentBatch);
		}
		response.sendRedirect("summary.jsp");
	}

}
